package com.lingshi.shopping_admin_service.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingshi.common.entity.Admin;
import com.lingshi.common.entity.AdminRole;
import com.lingshi.common.entity.Permission;
import com.lingshi.common.service.AdminService;
import com.lingshi.shopping_admin_service.mapper.AdminMapper;
import com.lingshi.shopping_admin_service.mapper.AdminRoleMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@DubboService
@Transactional
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private AdminRoleMapper adminRoleMapper;


    @Override
    public void add(Admin admin) {
        adminMapper.insert(admin);
    }

    @Override
    public void update(Admin admin) {
        adminMapper.updateById(admin);
    }

    @Override
    public void delete(Long aid) {
        //删除管理员角色中间表数据
        LambdaQueryWrapper<AdminRole> updateChainWrapper = new LambdaQueryWrapper<>();
        updateChainWrapper.eq(AdminRole::getAid, aid);
        adminRoleMapper.delete(updateChainWrapper);
        //删除管理员
        adminMapper.deleteById(aid);
    }

    @Override
    public Admin findById(Long aid) {
        return adminMapper.findById(aid);
    }

    @Override
    public Page<Admin> search(int page, int size) {
        Page<Admin>  adminPage = adminMapper.selectPage(new Page<>(page, size), null);
        return adminPage;
    }

    @Override
    public void updateRoleToAdmin(Long aid, Long[] rids) {
        // 删除用户的所有角色
        LambdaUpdateWrapper<AdminRole> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(AdminRole::getAid,aid);
        adminRoleMapper.delete(updateWrapper);
        // 重新添加管理员角色
        for (Long rid : rids) {
            AdminRole adminRole = new AdminRole();
            adminRole.setAid(aid);
            adminRole.setRid(rid);
            adminRoleMapper.insert(adminRole);
        }
    }

    @Override
    public Admin findByAdminName(String username) {
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username",username);
        Admin admin = adminMapper.selectOne(queryWrapper);
        return admin;
    }

    @Override
    public List<Permission> findAllPermission(String username) {
        return adminMapper.findAllPermission(username);
    }


}
